#include "position_manager.h"
#include <map>
#include <sstream>
#include <iomanip>
#include <cstring>
#include <iostream>

// 静态变量
static std::map<std::string, StockPosition> positions;  // 存储所有持仓信息
// static char positionsInfo[2048];  // 存储所有持仓信息的JSON字符串
static bool isInitialized = false;

// // 更新持仓信息JSON字符串
// void updatePositionsInfo() {
//     std::stringstream ss;
//     ss << "{\"positions\":[";
//     bool first = true;
//     for (const auto& pair : positions) {
//         if (!first) {
//             ss << ",";
//         }
//         first = false;
//         const auto& pos = pair.second;
//         ss << "{\"code\":\"" << pos.stockCode 
//            << "\",\"quantity\":" << pos.quantity
//            << ",\"currentPrice\":" << pos.currentPrice
//         //    << ",\"marketValue\":" << pos.marketValue
//            //<< ",\"profit\":" << pos.profit 
//            << "}";
//     }
//     // ss << "],\"totalCount\":" << positions.size()
//     //    << ",\"totalMarketValue\":" << std::fixed << std::setprecision(2) << getTotalMarketValue()
//     //    << ",\"totalProfit\":" << getTotalProfit() << "}";
//     strncpy(positionsInfo, ss.str().c_str(), sizeof(positionsInfo) - 1);
//     positionsInfo[sizeof(positionsInfo) - 1] = '\0';
// }

// // 计算单个持仓的市值和盈亏
// void calculatePositionMetrics(StockPosition& position) {
//     position.marketValue = position.quantity * position.currentPrice;
//     position.profit = position.marketValue - (position.quantity * position.costPrice);
// }

// 初始化持仓管理器
POSITION_API void initPositionManager() {
    if (!isInitialized) {
        positions.clear();
        //updatePositionsInfo();
        isInitialized = true;
    }
}

// 添加或更新股票持仓
POSITION_API bool updateStockPosition(const char* stockCode,
                                    int quantity, double currentPrice) {
    // std::cout << "#58 更新持仓: " << stockCode << " " << quantity << " " << currentPrice << std::endl;
    if (!isInitialized) {
        initPositionManager();
    }
    if (!stockCode || quantity <= 0 || currentPrice <= 0) {
        return false;
    }
    // std::cout << "#61 更新持仓: " << stockCode << " " << quantity << " " << currentPrice << std::endl;

    StockPosition& position = positions[stockCode];
    strncpy(position.stockCode, stockCode, sizeof(position.stockCode) - 1);
    position.quantity += quantity;
    position.currentPrice = currentPrice;
    // calculatePositionMetrics(position);

    // updatePositionsInfo();
    // std::cout << "#65 更新持仓成功: " << stockCode << " " << quantity << " " << currentPrice << std::endl;
    return true;
}

// 减少股票持仓
POSITION_API bool decreaseStockPosition(const char* stockCode, int quantity) {
    if (!isInitialized) {
        initPositionManager();
    }

    if (!stockCode || quantity <= 0) {
        return false;
    }

    auto it = positions.find(stockCode);
    if (it == positions.end() || it->second.quantity < quantity) {
        return false;
    }

    it->second.quantity -= quantity;
    if (it->second.quantity == 0) {
        positions.erase(it);
    } else {
        // calculatePositionMetrics(it->second);
    }

    // updatePositionsInfo();
    return true;
}

// 获取指定股票的持仓信息
POSITION_API bool getStockPosition(const char* stockCode, StockPosition* position) {
    if (!isInitialized || !stockCode || !position) {
        return false;
    }

    auto it = positions.find(stockCode);
    if (it == positions.end()) {
        return false;
    }

    *position = it->second;
    return true;
}

// 获取所有持仓股票的数量
POSITION_API int getTotalStockCount() {
    if (!isInitialized) {
        initPositionManager();
    }
    return positions.size();
}

// 获取所有持仓的市值总和
POSITION_API double getTotalValue() {
    if (!isInitialized) {
        initPositionManager();
    }

    double total = 0.0;
    for (const auto& pair : positions) {
        total += pair.second.currentPrice*pair.second.quantity;
    }
    return total;
}

// 获取所有持仓的盈亏总和
POSITION_API double getTotalProfit() {
    if (!isInitialized) {
        initPositionManager();
    }

    double total = 0.0;
    // for (const auto& pair : positions) {
    //     total += pair.second.profit;
    // }
    return total;
}

// // 获取所有持仓的详细信息
// POSITION_API const char* getAllPositionsInfo() {
//     if (!isInitialized) {
//         initPositionManager();
//     }
//     return positionsInfo;
// }

// 更新指定股票的当前价格
POSITION_API bool updateStockPrice(const char* stockCode, double currentPrice) {
    if (!isInitialized || !stockCode || currentPrice <= 0) {
        return false;
    }

    auto it = positions.find(stockCode);
    if (it == positions.end()) {
        return false;
    }

    it->second.currentPrice = currentPrice;
    // calculatePositionMetrics(it->second);
    // updatePositionsInfo();
    return true;
}

// 清空所有持仓
POSITION_API void clearAllPositions() {
    if (!isInitialized) {
        initPositionManager();
    }

    positions.clear();
    // updatePositionsInfo();
} 